﻿using Cloud.Core.Data;
using Cloud.Dto;
using Cloud.Entity;
using Cloud.Service.Base;
using Cloud.UnitOfWork;
using Cloud.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace Cloud.Service.User
{
    public class UserService :BaseService, IUserService
    {
        //private readonly IRepository<Sys_User> _userRepository;
        //private readonly IRepository<Sys_Role> _roleRepository;
        //private readonly IRepository<Sys_Role_User> _roleUserRepository;
        //public UserService(
        //    IRepository<Sys_Role> _roleRepository,
        //    IRepository<Sys_Role_User> _roleUserRepository,
        //    IRepository<Sys_User> _userRepository
        //    )
        //{
        //    this._roleRepository = _roleRepository;
        //    this._roleUserRepository = _roleUserRepository;
        //    this._userRepository = _userRepository;
        //}
       // private readonly IUnitOfWork _unitOfWork;
       
       public UserService(IUnitOfWork unitOfWork):base(unitOfWork){}
        public async Task<PageList<SysUserDto>> GetUserPageListAsync(int pageIndex, int pageSze, string LoginName = null, string RelName = null, string Phone = null)
        {
            //var useList= _unitOfWork.SqlQuery<Sys_User>("select * from sys_user");
            Expression<Func<Sys_User, bool>> exp = c => c.IsDeleted == false;
            if (!string.IsNullOrEmpty(LoginName))
            {
                exp = exp.And(c => c.LoginName.Contains(LoginName));
            }
            if (!string.IsNullOrEmpty(Phone))
            {
                exp = exp.And(c => c.Phone.Contains(Phone));
            }
            if (!string.IsNullOrEmpty(RelName))
            {
                exp = exp.And(c => c.RelName.Contains(RelName));
            }

            var query = await _unitOfWork.GetRepository<Sys_User>().LoadAsync(exp);
            var roleQuery = from t1 in await _unitOfWork.GetRepository<Sys_Role>().LoadAsync(c => c.IsDeleted == false)
                            join t2 in await _unitOfWork.GetRepository<Sys_Role_User>().LoadAsync()
                            on t1.Id equals t2.RoleID
                            select new { t1, t2 };

            query = query.OrderByDescending(c => c.Id);
            var dtoQuery = query.Select(c => new SysUserDto()
            {
                LoginID = c.Id,
                LoginName = c.LoginName,
                Email = c.Email,
                RelName = c.RelName,
                IsAdmin = c.IsAdmin,
                Phone = c.Phone,
                RoleList = roleQuery.Where(e => e.t2.UserID == c.Id).Select(t => new RoleDto() { RoleId = t.t1.Id, RoleName = t.t1.Name }).ToList()
            });
            var pageList = new PageList<SysUserDto>(dtoQuery, pageIndex, pageSze);

            return pageList;
        }
        private int _userId;
        public IUserService Init(int _userId)
        {
            this._userId = _userId;
           
            return this;
        }
        public SysUserDto Info
        {
            get
            {
                var model = new SysUserDto()
                {
                    LoginID = _userId
                };
                if (model.LoginID != 0)
                {
                    var entity = _unitOfWork.GetRepository<Sys_User>().Get(model.LoginID);
                    if (entity == null)
                    {
                        throw new Exception("要查找的对象不存在");
                    }
                    model.LoginName = entity.LoginName;
                    model.Phone = entity.Phone;
                    model.LoginPwd= CryptHelper.DecryptDES(entity.LoginPwd, entity.SaltKey);
                    model.IsAdmin = entity.IsAdmin;
                    model.Email = entity.Email;
                    model.RelName = entity.RelName;
                    model.RoleList = (from t1 in _unitOfWork.GetRepository<Sys_Role>().Entities
                                      join t2 in _unitOfWork.GetRepository<Sys_Role_User>().Entities
                                      on t1.Id equals t2.RoleID
                                      where t2.UserID == model.LoginID && t1.IsDeleted == false
                                      select new RoleDto() { RoleId = t1.Id, RoleName = t1.Name }).ToList();
                }
                return model;

            }
            set
            {
                using (var scope = _unitOfWork.BeginTransaction())
                {
                    var model = value;
                    var dt = DateTime.Now;
                    int userId = 0;
                    if (model.LoginID == 0)
                    {
                        //随机数
                        Random random = new Random();
                        string SaltKey = null;
                        bool MemberTrue = true;
                        //获取8位加解密字符串
                        do
                        {
                            SaltKey = CommonHelper.GetRandomNumber(10000000);
                            int nums = _unitOfWork.GetRepository<Sys_User>().Entities.Where(c => c.IsDeleted == false && c.IsDimission == false && c.SaltKey == SaltKey).Count();
                            if (nums == 0)
                            {
                                MemberTrue = false;
                            }
                        }
                        while (MemberTrue);
                        //加密密码
                        model.LoginPwd = CryptHelper.EncryptDES(model.LoginPwd, SaltKey);
                        model.SaltKey = SaltKey;
                        var hasLoginName = _unitOfWork.GetRepository<Sys_User>().Entities.Where(c => c.IsDeleted == false && c.IsDimission == false && c.LoginName == model.LoginName).Any();
                        if (hasLoginName)
                        {
                            throw new Exception("登录名已存在");
                        }
                        var entity = new Sys_User()
                        {
                            LoginName = model.LoginName,
                            LoginPwd=model.LoginPwd,
                            CreateTime = dt,
                            SaltKey=model.SaltKey,
                            CreateId = model.AccountId,
                            Phone = model.Phone,
                            IsAdmin = model.IsAdmin,
                            Email = model.Email,
                            RelName = model.RelName,
                        };
                        _unitOfWork.GetRepository<Sys_User>().Insert(entity);
                        userId = entity.Id;

                    }
                    else
                    {
                        var entity = _unitOfWork.GetRepository<Sys_User>().Get(model.LoginID);
                        if (entity == null)
                        {
                            throw new Exception("要修改的记录不存在");
                        }
                        if (entity.LoginName!=model.LoginName)//修改了登录名
                        {
                            var hasLoginName = _unitOfWork.GetRepository<Sys_User>().Entities.Where(c => c.IsDeleted == false && c.IsDimission == false && c.LoginName == model.LoginName).Any();
                            if (hasLoginName)
                            {
                                throw new Exception("登录名已存在");
                            }
                        }
                        entity.LoginName = model.LoginName;
                        entity.LoginPwd = CryptHelper.EncryptDES(model.LoginPwd, entity.SaltKey);
                        entity.Phone = model.Phone;
                        entity.IsAdmin = model.IsAdmin;
                        entity.Email = model.Email;
                        entity.RelName = model.RelName;
                        _unitOfWork.GetRepository<Sys_User>().Update(entity);
                        userId = entity.Id;

                        var roleUserEntityList = _unitOfWork.GetRepository<Sys_Role_User>().Entities.Where(c => c.UserID == entity.Id).ToList();
                        _unitOfWork.GetRepository<Sys_Role_User>().Delete(roleUserEntityList);
                    }
                    List<Sys_Role_User> newRoleUserEntityList = new List<Sys_Role_User>();
                    model.RoleList.ForEach(c =>
                    {
                        newRoleUserEntityList.Add(new Sys_Role_User()
                        {
                            RoleID = c.RoleId,
                            UserID = userId,
                            CreateId = model.AccountId,
                            CreateTime = dt,

                        });
                    });
                    _unitOfWork.GetRepository<Sys_Role_User>().Insert(newRoleUserEntityList);

                    scope.Commit();
                }
            }
        }

        public async Task Delete(int id)
        {
            using (var scope = _unitOfWork.BeginTransaction())
            {
                var roleUserEntityList =await _unitOfWork.GetRepository<Sys_Role_User>().GetListAsync(c=>c.UserID== id);
               await _unitOfWork.GetRepository<Sys_Role_User>().DeleteAsync(roleUserEntityList);
                var entity = await _unitOfWork.GetRepository<Sys_User>().GetAsync(id);
                if (entity == null)
                {
                    throw new Exception("要查找的对象不存在");
                }
                entity.IsDeleted = true;
                var updatedPropertyList = PropertyExpression<Sys_User>.Init.Property(c => c.IsDeleted).ToList();
                await _unitOfWork.GetRepository<Sys_User>().UpdateAsync(entity, true, updatedPropertyList);
                scope.Commit();
            }

        }
    }
}
